/*
 *   此商城的的聊天系统采用uniapp官方websocket api： https://uniapp.dcloud.io/api/request/websocket
 *   uni.connectSocket  建立链接
 *   uni.onSocketOpen   监听WebSocket连接打开事件
 *   uni.onSocketMessage  监听WebSocket接受到服务器的消息事件
 *   uni.sendSocketMessage  通过 WebSocket 连接发送数据
 *  */
import {
	LIVESOCKET,SERVERTAPI
} from "./../config/index";
let timer = null;

const im = () => {
	return;
	uni.connectSocket({
		url: LIVESOCKET,
		header: {
			'content-type': 'application/json'
		},
		method: 'GET',
		success: res => {
			console.log(`Websocket尝试连接${LIVESOCKET}✅...`)
		},
		fail: res => {
			console.log(`${LIVESOCKET}连接尝试失败❌`)
		}
	})

	uni.onSocketOpen(() => {
		console.info(`${LIVESOCKET} 连接打开onSocketOpen 开启心跳机制💚...`);
		timer = setInterval(() => {
			uni.sendSocketMessage({
				data: JSON.stringify({
					type: "ping",
					id: uni.getStorageSync("token"),
				}),
			});
		}, 9000);
	});


	uni.onSocketMessage((res) => {
		const data = JSON.parse(res.data);
		if (data.type === "init") {
			const client_id = data.data.client_id
			if (uni.getStorageSync("token") != '') {
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: "bind_id",
						id: uni.getStorageSync("token"),
						client_id,
					}),
				});
				uni.setStorageSync('client_id', client_id)
			}
		}
		
		if (data.type === "say") {
			console.log("say触发")
			uni.sendSocketMessage({
				data: JSON.stringify({
					type: "imcountnum",
					id: uni.getStorageSync("token"),
				}),
			});
		}
		
		
		if(data.type == "imcountnum"){
			let imcountnum = uni.getStorageSync("imcountnum") || 0;
			let imcountnumtips = uni.getStorageSync("imcountnumtips") || 0;
			if (uni.getStorageSync("token") != '') {
				imcountnum = data.data.imcountnum
				imcountnumtips = data.data.imcountnumtips
				let syncImcountnum = uni.getStorageSync("imcountnum") || imcountnum
				let syncimcountnumtips = uni.getStorageSync("imcountnumtips") || imcountnumtips
				// console.log("=================================syncImcountnum",syncImcountnum)
				//如果获取的数据大于历史消息就播放调用声音提醒
				uni.setStorageSync('imcountnum', imcountnum)
				uni.setStorageSync('imcountnumtips', imcountnumtips)
				if(imcountnum > syncImcountnum){
					message.start()
				}
			}
		}

	});
	
	
	var message = {
		start:function(){
			// #ifdef APP-PLUS
			// let main = plus.android.runtimeMainActivity();
			// let RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
			// let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
			// let MediaPlayer = plus.android.importClass("android.media.MediaPlayer");
			// let player = MediaPlayer.create(main, uri);
			// player.setLooping(false);
			// player.prepare();
			// player.start();
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = SERVERTAPI+"/static/message/message.mp3";
			innerAudioContext.onPlay(() => {
				console.log("开始播放");
			});
			innerAudioContext.play();
			// #endif
	
			// #ifndef APP-PLUS
			(function (argument) {
				console.log("new mess")
				// 音频文件
				var src = SERVERTAPI+"/static/message/message.mp3";
				// 初始化Aduio
				var audio = new Audio();
				var playPromise;
				audio.src = src;
				playPromise = audio.play();
				if (playPromise) {
					playPromise.then(() => {
						// 音频加载成功
						// 音频的播放需要耗时
						setTimeout(()=>{console.log("done.");}, audio.duration * 3000); // audio.duration 为音频的时长单位为秒
					}).catch((e) => {
						console.log(e)
					});
				}
			})();
			// #endif
		}
	};

	uni.onSocketClose(function(res) {
		console.log(res);
		console.log('WebSocket 已关闭！');
		// #ifdef MP-WEIXIN
		im();
		// #endif
	});
	uni.onSocketError(res => {
		clearInterval(timer);
		// console.error(`📵${LIVESOCKET}WebSocket连接打开失败，请检查！`);
		im();
	});
}
export default im
